<template>
	<div>
		<div class="container">
			<div class="handle-box">
				<el-select v-model="query.area" placeholder="图鉴地区" class="handle-select mr10" clearable>
					<el-option :key="index + 1" :label="item" :value="item" v-for="(item, index) in areaList"></el-option>
				</el-select>
				<el-input v-model="query.name" placeholder="宝可梦名称" class="handle-input mr10"></el-input>
				<el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
				<el-button type="primary" :icon="Plus" @click="showAdd('add')">新增</el-button>
			</div>
			<el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header"
				v-loading="tableLoading">
				<el-table-column prop="id" label="编号" width="55" align="center"></el-table-column>
				<el-table-column prop="name" label="名称"></el-table-column>
				<el-table-column label="所属地区">
					<template #default="scope">{{ scope.row.area }}</template>
				</el-table-column>
				<el-table-column label="图片" align="center">
					<template #default="scope">
						<el-image class="table-td-thumb" :src="'http://127.0.0.1:7001' + scope.row.image" :z-index="10"
							:preview-src-list="['http://127.0.0.1:7001' + scope.row.image]" preview-teleported>
						</el-image>
					</template>
				</el-table-column>
				<el-table-column label="属性" align="center">
					<template #default="scope">
						<div class="attributes">
							<div class="attr" :class="getAttrClass(attr)" v-for="attr in JSON.parse(scope.row.attribute)"
								:key="attr">{{ attr }}
							</div>
						</div>
					</template>
				</el-table-column>
				<el-table-column label="进化链" align="center" prop="evolution"></el-table-column>
				<el-table-column label="种族值" align="center" prop="race"></el-table-column>
				<el-table-column prop="outline" :show-overflow-tooltip="true" label="描述" align="center"></el-table-column>
				<el-table-column label="操作" width="220" align="center">
					<template #default="scope">
						<el-button text :icon="Edit" @click="showAdd('edit', scope.row)" v-permiss="3">
							编辑
						</el-button>
						<el-button text :icon="Delete" class="red" @click="handleDelete(scope.row)" v-permiss="3">
							删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div class="pagination">
				<el-pagination background layout="total, prev, pager, next" :current-page="query.pageIndex"
					:page-size="query.pageSize" :total="pageTotal" @current-change="handlePageChange"></el-pagination>
			</div>
		</div>
		<!-- 新增/编辑弹出框 -->
		<el-dialog :title="addForm.title + '宝可梦'" v-model="addVisible" width="50%" align-center @close="()=>{addRef.resetFields()}">
			<el-form label-position="left" label-width="80px" v-loading="addLoading" :rules="addRules" :model="addForm"
				ref="addRef">
				<el-form-item label="图鉴编号" prop="id">
					<el-input v-model="addForm.id" placeholder="图鉴编号"></el-input>
				</el-form-item>
				<el-form-item label="名称" prop="name">
					<el-input v-model="addForm.name" placeholder="名称"></el-input>
				</el-form-item>
				<el-form-item label="所属地区" prop="area">
					<el-select v-model="addForm.area" placeholder="图鉴地区" class="handle-select mr10">
						<el-option :key="index + 1" :label="item" :value="item"
							v-for="(item, index) in areaList"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="种族值" prop="race">
					<el-input v-model="addForm.race"></el-input>
				</el-form-item>
				<el-form-item label="属性" prop="attribute">
					<el-select-v2 style="width: 180px" v-model="addForm.attribute" placeholder="属性" :multiple-limit="2"
						multiple :options="options"></el-select-v2>
				</el-form-item>
				<el-form-item label="图片" prop="file">
					<el-upload action="#" list-type="picture-card" :auto-upload="false" :multiple="false" ref="uploadRef"
						:limit="1" :data="addForm" :before-upload="beforeUpload">
						<el-icon>
							<Plus />
						</el-icon>
					</el-upload>
				</el-form-item>
				<el-form-item label="进化链" v-show="addForm.title === '编辑'" prop="evolution">
					<el-tag v-for="(tag, index) in addForm.evolution" :key="tag" class="mx-1" closable
						:disable-transitions="false" @close="handleClose(index)">
						{{ (index === 0 ? '一阶段-编号' : index === 1 ? '二阶段-编号' : '三阶段-编号') }}{{ tag }}
					</el-tag>
					<el-button class="button-new-tag ml-1" size="small" @click="showEvo">添加进化</el-button>
					<!-- 进化弹窗 -->
					<el-dialog title="选择进化" v-model="evoVisible" width="30%" align-center>
						<div class="evo name">
							<span :style="{ width: '50px' }">名称</span>
							<el-input v-model="evoInfo.key"></el-input>
							<el-button>搜索</el-button>
						</div>
						<el-table :data="evoInfo.tableData" border class="table" ref="multipleTable" highlight-current-row
							header-cell-class-name="table-header" @current-change="EvoCurrentChange">
							<el-table-column prop="id" label="编号" width="55" align="center"></el-table-column>
							<el-table-column label="图片" align="center">
								<template #default="scope">
									<el-image class="table-td-thumb" :src="'http://127.0.0.1:7001' + scope.row.image"
										:z-index="10">
									</el-image>
								</template>
							</el-table-column>
							<el-table-column prop="name" label="名称"></el-table-column>
						</el-table>
						<div class="pagination">
							<el-pagination background layout="total, prev, pager, next" :current-page="evoInfo.pageIndex"
								:page-size="evoInfo.pageSize" :total="evoInfo.pageTotal"
								@current-change="handlePageChangeEvo"></el-pagination>
							<el-button @click="addEvo" v-loading="addLoading">添加</el-button>
						</div>
					</el-dialog>
				</el-form-item>
				<el-form-item label="描述" prop="outline">
					<el-input v-model="addForm.outline" type="textarea"></el-input>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="closeAdd(addRef)">取 消</el-button>
					<el-button type="primary" @click="submitAdd(addRef)">确 定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="basetable">
import { ref, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { UploadInstance } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus';
import { Delete, Edit, Search, Plus } from '@element-plus/icons-vue';
import { getPage, deletePokemon } from '../api/pokemon'
import { getAttrClass } from '../utils/attribute'
import axios from '../utils/request'

interface TableItem {
	id: number;
	name: string;
	area: string;
	attribute: string;
	evolution: string;
	image: string;
	outline: string;
	race: string
}
const attributeList = ['一般', '火', '水', '草', '电', '冰', '格斗', '毒', '地面', '飞行', '超能力', '虫', '岩石', '幽灵', '龙', '恶', '钢', '妖精'];
const options = ref(
	attributeList.map((item) => ({
		value: item,
		label: item,
	}))
)
const query = reactive({
	name: '',
	area: '',
	pageIndex: 1,
	pageSize: 8
});
const tableLoading = ref(false)
const tableData = ref<TableItem[]>([]);
const pageTotal = ref(0);
const areaList = ['关都地区', '城都地区', '丰缘地区', '神奥地区', '合众地区', '卡洛斯地区', '阿罗拉地区', '伽勒尔地区', '洗翠地区', '帕迪亚地区'];
// 获取表格数据
const getData = () => {
	tableLoading.value = true;
	getPage({ page: query.pageIndex, limit: query.pageSize,name:query.name,area:query.area }).then((res: any) => {
		if (res.code !== 200) return ElMessage.error(res.msg || '获取宝可梦列表失败')
		const { data } = res
		tableData.value = data.data
		pageTotal.value = data.total
	}).finally(() => tableLoading.value = false)
};
getData();

// 查询操作
const handleSearch = () => {
	query.pageIndex = 1;
	getData();
};
// 分页导航
const handlePageChange = (val: number) => {
	query.pageIndex = val;
	getData();
};

// 删除操作
const handleDelete = (row: any) => {
	// 二次确认删除
	ElMessageBox.confirm('确定要删除吗？', '提示', {
		type: 'warning'
	}).then(() => {
		deletePokemon({ id: row.id }).then((res: any) => {
			if (res.code !== 200) return ElMessage.error(res.msg || '删除失败')
			ElMessage.success(res.msg || '删除成功！')
			getData();
		})

	})
};

// 表格新增时弹窗和保存
const addVisible = ref(false);
const addRef:any = ref();
const addForm = reactive({
	title: '新增',
	id: '',
	name: '',
	attribute: [],
	race: '',
	evolution: [] as any,
	outline: '',
	area: '',
});
const addRules: FormRules = {
	id: [{ required: true, message: '请输入编号', trigger: 'blur' }],
	name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
	attribute: [{ required: true, message: '请输入属性', trigger: 'blur' }],
	race: [{ required: true, message: '请输入种族值', trigger: 'blur' }],
	outline: [{ required: true, message: '请输入描述', trigger: 'blur' }],
	area: [{ required: true, message: '请输入所属地区', trigger: 'blur' }],
};
const uploadRef = ref<UploadInstance>()
const addLoading = ref(false)
// 上传图片加表单
const beforeUpload = (file: any) => {
	addLoading.value = true;
	const fd = new FormData();
	const evolution = addForm.evolution;
	fd.append('file', file)
	fd.append('id', addForm.id);
	fd.append('name', addForm.name);
	fd.append('attribute', JSON.stringify(addForm.attribute));
	fd.append('race', addForm.race);
	fd.append('evolution', JSON.stringify(evolution));
	fd.append('outline', addForm.outline);
	fd.append('area', addForm.area);
	const url = addForm.title === '编辑' ? '/updatePokemon' : '/addPokemon';
	axios.post(url, fd, {
		headers: {
			'Content-Type': 'multipart/form-data'
		}
	}).then((res: any) => {
		if (res.code !== 200) return ElMessage.error('上传失败')
		addForm.id = '';
		addForm.name = '';
		addForm.attribute = [];
		addForm.race = '';
		addForm.evolution = [];
		addForm.outline = '';
		addForm.area = '';
		addVisible.value = false;
		ElMessage.success('成功')
		getData();
	}).finally(() => addLoading.value = false)
	return false;
}
const handleClose = (index: number) => {
	addForm.evolution.splice(index, 1)
}
const showAdd = (str?: string, row?: any) => {
	if (str === 'edit') {
		addForm.title = '编辑';
		addForm.id = row.id;
		addForm.name = row.name;
		addForm.attribute = JSON.parse(row.attribute);
		addForm.race = row.race;
		addForm.evolution = JSON.parse(row.evolution);
		addForm.outline = row.outline;
		addForm.area = row.area;
	} else {
		addForm.title = '新增'
		addForm.id = '';
		addForm.name = '';
		addForm.attribute = [];
		addForm.race = '';
		addForm.evolution = [];
		addForm.outline = '';
		addForm.area = '';
	}
	addVisible.value = true;
};
const submitAdd = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (valid) {
			uploadRef.value!.submit()
		} else {
			ElMessage.error('请正确输入表单信息')
		}
	})
};
const closeAdd = (formEl: any) => {
	addVisible.value = false;
}
// 进化弹窗相关
const evoVisible = ref(false)
const evoInfo = reactive({
	key: '',
	tableData: [] as any,
	pageIndex: 1,
	pageTotal: 0,
	pageSize: 5
})
const currentRow = ref()
const EvoCurrentChange = (val: any) => {
	currentRow.value = val
}
const showEvo = () => {
	evoVisible.value = true;
	getEvoData();
}
const getEvoData = () => {
	getPage({ page: evoInfo.pageIndex, limit: evoInfo.pageSize }).then((res: any) => {
		if (res.code !== 200) return ElMessage.error(res.msg || '获取宝可梦列表失败')
		const { data } = res
		evoInfo.tableData = data.data
		evoInfo.pageTotal = data.total
	})
}
const handlePageChangeEvo = (val: number) => {
	evoInfo.pageIndex = val;
	getEvoData();
}
const addEvo = () => {
	addForm.evolution.push(currentRow.value.id);
	console.log(addForm.evolution)
	evoVisible.value = false;
}
</script>

<style scoped>
.handle-box {
	margin-bottom: 20px;
}

.handle-select {
	width: 120px;
}

.handle-input {
	width: 300px;
}

.table {
	width: 100%;
	font-size: 14px;
}

.red {
	color: #F56C6C;
}

.mr10 {
	margin-right: 10px;
}

.table-td-thumb {
	display: block;
	margin: auto;
	width: 40px;
	height: 40px;
}

.pagination {
	display: flex;
	justify-content: space-between;
}

.evo.name {
	display: flex;
	justify-content: space-between;
	margin-bottom: 15px;
}
</style>
